import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_wan_android/data/banner/banner_entity.dart';

/// 图片轮播图
class CarouselImage extends StatefulWidget {
  final List<BannerEntity> list;
  final void Function(int index) onPageChange;

  const CarouselImage({
    super.key,
    required this.list,
    required this.onPageChange,
  });

  @override
  State<CarouselImage> createState() => _CarouselImageState();
}

class _CarouselImageState extends State<CarouselImage> {
  late PageController _pageController;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: widget.list.length * 100,
      onAttach: _onAttach,
      onDetach: onDetach,
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _buildNotificationListener();
  }

  /// 用户手动滑动时 开始/停止 定时器
  NotificationListener<ScrollNotification> _buildNotificationListener() {
    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is UserScrollNotification) {
          if (notification.direction != ScrollDirection.idle) {
            cancelTimer(); // 手动滑动开始
          } else {
            startTimer(); // 手动滑动结束
          }
        }
        return false;
      },
      child: _buildAspectRatio(),
    );
  }

  /// 设置布局宽高
  AspectRatio _buildAspectRatio() {
    return AspectRatio(aspectRatio: 16 / 9, child: _buildPageView());
  }

  /// 构建pageView
  PageView _buildPageView() {
    return PageView.builder(
      controller: _pageController,
      onPageChanged: (index) {
        widget.onPageChange(convertRealIndex(index));
      },
      itemCount: null,
      itemBuilder: (context, index) {
        final realIndex = convertRealIndex(index);
        final entity = widget.list[realIndex];
        return _buildItem(entity);
      },
    );
  }

  Widget _buildItem(BannerEntity entity) {
    return GestureDetector(
      onTap: () {
        debugPrint("点击${entity.title}");
      },
      child: Image.network(entity.imagePath, fit: BoxFit.fill),
    );
  }

  /// 无限滚动的index 转为 对应的 数组真实index
  int convertRealIndex(int index) {
    return index % widget.list.length;
  }

  void _onAttach(ScrollPosition position) {
    startTimer();
  }

  void onDetach(ScrollPosition position) {
    cancelTimer();
  }

  void startTimer() {
    cancelTimer();
    debugPrint("开始定时器");
    _timer = Timer.periodic(Duration(milliseconds: 3500), (timer) {
      _pageController.nextPage(
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    });
  }

  void cancelTimer() {
    if (_timer != null && _timer!.isActive) {
      debugPrint("停止定时器");
      _timer?.cancel();
      _timer = null;
    }
  }
}
